
//******************************************************************************************************
//*TIMEPICKER FUNCTIONALITIES START HERE
//******************************************************************************************************
var initial_textfield_value;
function load_time_picker_anim(){
    $(".time_picker").each(function(){
        $(this).find('div').bind({
            mouseenter: function(){
                $(this).toggleClass('entered')
            },
            mouseleave: function(){
                $(this).toggleClass('entered')
            },
            click: function(){
                if(!$(this).hasClass('selected')){
                    $(".time_picker div").each(function(){
                        $(this).removeClass('selected');
                    });
                }
                //set selected time into the input field
                $("#"+$(this).parent().find(".focused_time_field_id").html()).val($(this).find(".time_picked").html());
                $(this).toggleClass('selected');
            },
        });
    });
    $(".time_picker").mouseout(function(){
        var timefield = $("#"+$(this).find(".focused_time_field_id").html());
        if(timefield.length===0) {
            return;
        }
        else if(!timefield.is(":hover") && !timefield.is(":focus")){
//            alert("here");
            timefield.parent().find(".active_tp").each(function(){
                $(this).removeClass("active_tp");
            });
            $(this).parent().find(".time_picker").each(function(){
                $(this).remove();
            });
            }
    });
}
function load_time_picker_triggers(){
    $(".time").focusout(function(){
        //detects changes of the start time, for auto-adjusting the end time automatically
        //it also calls the PAIR validation function 
        auto_adjust_timepickers_new_time_difference($(this),initial_textfield_value);
       
        var time_picker = $(this).parent().find(".time_picker");
        var timefield = $(this);
        if(time_picker.length===0) return;
        else if(time_picker.length>1){
            for(var i=1; i<time_picker.length;i++){
                time_picker[i].remove();
            }
            time_picker = time_picker[0];
        }
        setTimeout(function(){
            if(!time_picker.is(":focus") && !time_picker.is(":hover")){
                time_picker.remove();
                timefield.parent().find(".active_tp").each(function(){
                    $(this).removeClass("active_tp");
                });
            }
        },100);
    });
    //TRIGGERS THE TIMEPICKER for THIS TEXTFIELD
    $(".time").focus(function(){
        var valid_format_textfield  = validate_textfield_hours_format($(this));
        
        //saves the current value of the start time, if valid, for auto-adjusting the end time automatically
        if($(this).hasClass("class_start") && valid_format_textfield){
            initial_textfield_value = $(this).val();
        }else{
            initial_textfield_value = "";
        }
        
        remove_all_created_timepickers();
        $(this).parent().append($(".time_picker").clone().removeClass("main_copy").css("display","block"));
        $(this).addClass("active_tp");//marks active time picker
        
        $(this).parent().find(".time_picker")
                .find(".focused_time_field_id").html($(this).attr("id")).hide();
        $(this).parent().find(".time_picker").position({
            of: $(this),
            my: "left top",
            at: "left bottom",
            collision: "none none"
        });
//        var valid_hours = validate_form_hours_format($(this).parents('form:first').attr("id"));
        if(valid_format_textfield) {
            texfield_to_timepicker($(this));
        }
        auto_adjust_end_timepicker_offsets($(this));
        adjust_scrolls_for_timepicker($(this));
        load_time_picker_anim();
    });
    $(".time").keyup(function(){
        validate_textfield_hours_format($(this));
        texfield_to_timepicker($(this));
    });
}
//applies the difference between the start time's and end time's textfields into the end_time timepicker.
//detects changes of the start time, for auto-adjusting the end time automatically
//TO BE CALLED ON FOCUSOUT OF A TEXTFIELD
function auto_adjust_timepickers_new_time_difference(time_textfield,initial_textfield_value){
        setTimeout(function(){ //gives time for the timepicker. it may make changes in the textfield and needs time to effectivate it
            var end_timefield = time_textfield.parent().find(".class_end");
            if(time_textfield.hasClass("class_start")//this function should only be triggered by the start time field
                && !time_textfield.hasClass("format_invalid")
                && time_textfield.val()!==initial_textfield_value
                && validate_time_string(initial_textfield_value)
                && validate_time_string(time_textfield.val())
                && validate_time_string(end_timefield.val())
            ){
               var initial = parseTime(initial_textfield_value);
               var initial_mins = initial.hh*60 + initial.mm;
               
                var current = parseTime(time_textfield.val());
               var current_mins = current.hh*60 + current.mm;
               
                var time_difference_mins = current_mins - initial_mins;
               
                var end_time = parseTime(end_timefield.val());
                var end_time_mins = end_time.hh*60 + end_time.mm;
               
               //validates difference in relation to the initial hour value=> because the new one should generate another end time
//            applies the time difference in the start time onto the end time
               if(end_time_mins>=initial_mins && time_difference_mins!=0){//validates format and order
                //detects and change the end time
                    var hours; 
                    var minutes;
                    
                    //atribuição de valores 
                    if(end_time_mins+time_difference_mins < 0){ //floor
                        hours = minutes = 0;
                    }else if(end_time_mins+time_difference_mins > 24*60) {//ceil
                        hours = 23;
                        minutes = 59;
                    }else{
                        hours= end_time.hh + parseInt((time_difference_mins-(time_difference_mins%60))/60);
                        minutes= end_time.mm+(time_difference_mins%60);
                    }
                    
                    if(minutes<0){
                        hours--;
                        minutes += 60;
                    }else if(minutes>=60){
                        hours++;
                        minutes -= 60;
                    }
                    //make it 2 digit
                    end_timefield.val((hours<10?"0":"")+hours+":"+(minutes<10?"0":"")+minutes);
                    
                    //adjustment calls for quick change (via TAB) between start/end time textfields
                    validate_textfield_hour_PAIR(end_timefield);
                    texfield_to_timepicker(end_timefield);
                    auto_adjust_end_timepicker_offsets(end_timefield);
                    adjust_scrolls_for_timepicker(end_timefield);
                }else 
                    initial_textfield_value="";
            }else 
                initial_textfield_value="";
        },200);
}
function auto_adjust_end_timepicker_offsets(textfield){
    if(!validate_textfield_hour_PAIR(textfield)){
        return false;
    }
    
    var end_timestamp ,start_timestamp;
    var class_time = textfield.parents(".class_time:first");
    
    //seta variaveis de tempo
    class_time.find(".class_start").each(function(){
        if(validate_textfield_hours_format($(this))){
            start_timestamp = parseTime($(this).val());
            start_timestamp = new Date(2000,0,1,start_timestamp.hh,start_timestamp.mm);
        }else return false;
    });
    //compara e calcula a diferença para o canvas
    class_time.find(".time_picker").each(function(){
        //se for um time picker de horario de fim, seta as diferenças
        if($("#"+$(this).find(".focused_time_field_id").html()).hasClass("class_end")){
            $(this).find(".time_picked").each(function(){
                end_timestamp = parseTime($(this).html());
                end_timestamp = new Date(2000,0,1,end_timestamp.hh,end_timestamp.mm);
                var  time_cell = $(this).parent();
                if(end_timestamp>start_timestamp){
                    time_cell.show();
                    var diff_time = (end_timestamp.getHours()*60+end_timestamp.getMinutes()) 
                            - (start_timestamp.getHours()*60+start_timestamp.getMinutes());
                    
                    //adjusting time format 
                    var minutes = diff_time%60;
                    var hours = parseInt((diff_time-minutes)/60);
                    var diff_display = " ("+((hours>0)?hours+"h":"");//set hours in display
                    diff_display+=((minutes>0)?minutes+"m":"") + ")";
                    
                    time_cell.find(".offset").html(diff_display);
                }else{
                    time_cell.hide();
                }
            });
        }
    });
}


function remove_all_created_timepickers(){
    $(".time_picker").each(function(){
        if(!$(this).hasClass("main_copy"))
            $(this).remove();
    });
    $(".active_tp").each(function(){
        $(this).removeClass(".active_tp");
    });
}
//if there's a value into the texfield, selects it into the time picker
function texfield_to_timepicker(textfield){
    var field_val = textfield.val();
    if(!validate_time_string(field_val)){
        return false;
    }
    field_val = field_val.split(":");

    if(field_val.length>=2){
        var aux = field_val[1].split("");
        switch(Math.round(parseInt(field_val[1])/30)){
            case 0: 
                field_val[1] = "00";
                break;
            case 1:
                field_val[1] = "30";
                break;
            case 2:
                field_val[1] = "00";
                field_val[0] = parseInt(field_val[0]);
                field_val[0] += parseInt(field_val[0])<23?1:0;//increments the hour field
                field_val[0] = ((parseInt(field_val[0]) < 10)? "0":"") + parseInt(field_val[0]);
                break;
        }
        
        field_val = field_val[0]+":"+field_val[1];
    }else return false;
    textfield.parent().find(".time_picked").each(function(){
        if(validate_time_string($(this).html())
        && field_val===$(this).html()){
            $(this).parent().parent().find(".selected").removeClass("selected");
            $(this).parent().addClass("selected");
        } 
    });
    return true;
}
function adjust_scrolls_for_timepicker(textfield){
    //scrolls accordion_element_content
    var time_picker = textfield.parent().find(".time_picker");
    if(time_picker.length!=1)
        return;
    var accordion_element_content = time_picker.parents(".accordion_element_content:first");
    var accordion_element_title_height = $(".accordion_element_title:first").height() + 2*parseInt($(".accordion_element_title:first").css('padding-top'));

    $("html, body").animate({
        scrollTop: (accordion_element_content.offset().top - accordion_element_title_height)
     }, 1000);
    
//    ajusta scroll somente se ha partes do timepicker que nao estao visiveis
    if(!isScrolledIntoView(time_picker)){
//        FORA DO CAMPO DE VISÃO ATUAL DO SCROLL. AJUSTA PARA QUE O FUNDO DO TIME PICKER SE ALINHE AO DO accordion_element_content
        //calcula offset
        var docViewTop = accordion_element_content.offset().top;// - parseInt(accordion_element_content.css("padding-top").replace("px",""));
        var docViewBottom = docViewTop + accordion_element_content.height()
                + parseInt(accordion_element_content.css("padding-bottom").replace("px",""))
                + parseInt(accordion_element_content.css("padding-top").replace("px",""));
        var elemTop = time_picker.offset().top;// + parseInt(accordion_element_content.css("padding-top").replace("px",""));;
        var elemBottom = elemTop + time_picker.height();// + parseInt(accordion_element_content.css("padding-bottom").replace("px",""));
        var offset = elemBottom - docViewBottom;
        accordion_element_content.animate({
            scrollTop: (accordion_element_content.scrollTop() + offset )
         }, 1000);
    }
    
    //correção de falhas: previne que time picker saia de baixo do timefield
    accordion_element_content.scroll(function(){
        var time_picker = accordion_element_content.find(".class_hours:first .time_picker");
        if(time_picker.length){
            time_picker.position({
                of: $("#"+time_picker.find(".focused_time_field_id").html()),
                my: "left top",
                at: "left bottom",
                collision: "none none"
            });
        }
    });
    
    //scrolls time_picker until the selected cell
    var selected = time_picker.find(".selected");
    var selected_scroll;
    
    if(selected.length===0 || selected.length>=2) return;
    else selected_scroll = parseInt(selected.position().top);
    
    if(selected_scroll>=60) selected_scroll-=60;
    else selected_scroll = 0;
    
    textfield.parent().find(".time_picker").scrollTop(selected_scroll);
}
function isScrolledIntoView(timepicker){
    var accordion_element_content = timepicker.parents(".accordion_element_content:first");
    var docViewTop = accordion_element_content.offset().top;// - parseInt(accordion_element_content.css("padding-top").replace("px",""));
    var docViewBottom = docViewTop + accordion_element_content.height()
            + parseInt(accordion_element_content.css("padding-bottom").replace("px",""))
            + parseInt(accordion_element_content.css("padding-top").replace("px",""));

    var elemTop = timepicker.offset().top;// + parseInt(accordion_element_content.css("padding-top").replace("px",""));;
    var elemBottom = elemTop + timepicker.height();// + parseInt(accordion_element_content.css("padding-bottom").replace("px",""));

    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom)
      && (elemBottom <= docViewBottom) &&  (elemTop >= docViewTop) );
}
//******************************************************************************************************
//*TIMEPICKER FUNCTIONALITIES END HERE
//******************************************************************************************************

